package edu.hebeu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.hebeu.R;
import edu.hebeu.adapters.ListOrderAdapter;
import edu.hebeu.entity.ListOrderResponse;
import edu.hebeu.network.API;
import edu.hebeu.network.APIConfig;
import edu.hebeu.network.MyCallback;

public class OrderActivity extends BaseActivity {

    private static String TAG = "OrderActivity";

    private int i; // 决定当前要显示的第几页数据
    private int total; // 保存共几页数据
    private String searchOrderCode; // 表示搜索的订单号

    private List<ListOrderResponse.Order> data;

    private SwipeRefreshLayout srl;
    private RecyclerView recycler_view;
    private EditText et_search;
    private Button btn_search;
    private ListOrderAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order;
    }

    @Override
    protected void initViews() {
        srl = (SwipeRefreshLayout) findViewById(R.id.srl);
        recycler_view = (RecyclerView) findViewById(R.id.recycler_view); // 获取RecyclerView组件
        et_search = (EditText) findViewById(R.id.et_search);
        btn_search = (Button) findViewById(R.id.btn_search);
        i = 1;
        searchOrderCode = null;
        data = new ArrayList<>();
        getFirstData();
    }

    private void show(List<ListOrderResponse.Order> orders) {
        // 创建布局管理器对象
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        // 设置水平
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        // 设置正向显示
        layoutManager.setReverseLayout(false);
        recycler_view.setLayoutManager(layoutManager); // 设置布局管理器

        // 创建适配器对象实例
        adapter = new ListOrderAdapter(orders);
        recycler_view.setAdapter(adapter);

        // 初始化监听器
        initListener();
    }

    /**
     * 该方法用来初始化监听器
     */
    private void initListener() {
        adapter.setOnItemClickListener(new ListOrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ListOrderResponse.Order order) {
                Bundle bundle = new Bundle();
                bundle.putString("code", order.getCode());

                Intent intent = new Intent(OrderActivity.this, OrderDetailActivity.class);
                intent.putExtra("order_data", bundle);
                startActivity(intent);
            }
        });

        // 给适配器对象添加上拉加载更多的监听器
        adapter.setOnUpPullListener(new ListOrderAdapter.OnUpPullListener() {
            @Override
            public void onUpPull(final ListOrderAdapter.LoadMoreHolder loadMoreHolder) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        i++; // 将要显示的页数自增1
                        if (i <= total) { // 如果当前要显示的页在总页面之内,则进行如下(继续加载请求数据)
                            Map<String, Object> params = new HashMap<>();
                            params.put("i", i); // 只传入参数 i=1，表示请求第一页的数据
                            params.put("user_username", getSPFile("username", ""));
                            params.put("code", searchOrderCode);
                            requestOrders(params, loadMoreHolder);
                        } else { // 否则,即数据已经全部加载了
                            showToast("没有找到更多的订单！", 0, false);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadMoreHolder.loadPrepare(ListOrderAdapter.LoadMoreHolder.LOADER_STATE_NORMAL); // 将状态设置为正常
                                }
                            });
                        }
                    }
                }, 1000);
            }
        });

        setDownPullUploadListener(); // 下滑事件的监听器

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchOrderCode = et_search.getText().toString(); // 将搜索的关键字修改
                getFirstData();
            }
        });
    }

    /**
     * 这个方法用来实现下拉刷新(给绑定下拉事件的监听和处理)
     */
    private void setDownPullUploadListener() {
        // 设置该加载圈的颜色
        srl.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary,
                R.color.colorPrimaryDark, R.color.colorDark, R.color.colorMoneyRed);
        srl.setEnabled(true); // 让该组件(刷新)可用
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchOrderCode = null; // 将搜索的关键字修改为空
                et_search.setText(null); // 将搜索文本框的值修改为空
                // 执行刷新数据的操作
                getFirstData();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 这里需要做两件事：1、让刷新停止；2、更新列表；
                        adapter.notifyDataSetChanged();
                        srl.setRefreshing(false);
                        showToast("刷新成功", 0, false);
                    }
                }, 2000);
            }
        });
    }

        /**
         * 首次加载数据的方法
         */
    private void getFirstData() {
        Map<String, Object> params = new HashMap<>();
        params.put("i", 1); // 只传入参数 i=1，表示请求第一页的数据
        params.put("username", getSPFile("username", ""));
        params.put("code", searchOrderCode);
        requestFirstOrders(params);
    }

    /**
     * 第一次加载订单信息的网络请求方法
     * @param params
     */
    private void requestFirstOrders(Map<String, Object> params) {
        String token = (String) getSPFile("token", "");
        API.requestConfig(APIConfig.URL.LIST_ORDER_URL, params, token)
            .postRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
                    final ListOrderResponse response = (ListOrderResponse) deSerialize(res, ListOrderResponse.class);
                    if (response == null) {
                        jumpActivity(LoginActivity.class, true);
                        showToast("身份验证失败，请重新登录", 0, true);
                    } else if (response.getCode() == 200) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                data.clear();
                                total = response.getPage().getTotal();
                                data.addAll(response.getPage().getOrders());
                                show(data);
                                Log.i(TAG, "Order响应：" + data.toString());
                            }
                        });
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    showToast("请求数据失败！", 0, true);
                }
            }, true);
    }

    /**
     * 请求加载更多订单信息的请求(除去第一次请求订单的其他请求)方法
     * @param params
     * @param loadMoreHolder
     */
    private void requestOrders(Map<String, Object> params, final ListOrderAdapter.LoadMoreHolder loadMoreHolder) {
        String token = (String) getSPFile("token", "");
        API.requestConfig(APIConfig.URL.LIST_ORDER_URL, params, token)
            .postRequest(new MyCallback() {
                @Override
                public void onSuccess(String res) {
                    final ListOrderResponse response = (ListOrderResponse) deSerialize(res, ListOrderResponse.class);
                    if (response == null) {
                        jumpActivity(LoginActivity.class, true);
                        showToast("身份验证失败，请重新登录", 0, true);
                    } else if (response.getCode() == 200) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                data.addAll(response.getPage().getOrders());
                                adapter.notifyDataSetChanged();
                                loadMoreHolder.loadPrepare(ListOrderAdapter.LoadMoreHolder.LOADER_STATE_LOADDING); // 将状态设置为正在加载
                            }
                        });
                    }
                }

                @Override
                public void onFailure(Exception e) {
                    showToast("请求数据失败！", 0, true);
                }
            }, true);

    }

}
